/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package battleship.game;

import battleship.ship.ShipType;
import java.util.List;
import util.MsgPrinter;

/**
 *
 * @author ali
 */
public class StateCheckWinner extends AbstractState{

    private static StateCheckWinner instance;
    private static AbstractState nextState;
    private boolean hasHumanWon = false;
    private boolean hasCompWon = false;

    private StateCheckWinner(AbstractState next) {
        nextState = next;
    }


    public static AbstractState getInstance(AbstractState next){
        instance = new StateCheckWinner(next);
        return instance;
    }
    
    @Override
    public void execute() {
        hasHumanWon = hasHumanWon();
        hasCompWon = hasCompWon();
    }

    @Override
    public StateType getNextState() {
        if(hasHumanWon || hasCompWon){
            nextState = StateGameEnd.getinstance();
       }
        return nextState;
    }

    private boolean hasHumanWon() {
        List<ShipType> ships = Game.getCompPlayer().getBoard().getShips();
        hasHumanWon = hasAllShipsSunk(ships);
        return hasHumanWon;
    }

    private boolean hasCompWon() {
        List<ShipType> ships = Game.getHumanPlayer().getBoard().getShips();
        hasCompWon = hasAllShipsSunk(ships);
        return hasCompWon;
    }

    private boolean hasAllShipsSunk(List<ShipType> ships){
        boolean hasAllShipsSunk = true;
        for(ShipType ship : ships){
            if(!ship.isSunk()){
                hasAllShipsSunk = false;
                break;
            }
        }
//        MsgPrinter.print("Has All Ships Sunk : "+Boolean.toString(hasAllShipsSunk));
        return hasAllShipsSunk;
    }
}
